const UserService = require("../../services/admin/UserService");
const JWT = require("../../utils/JWT");
const path = require("path");
const fs = require("fs");

// 异步删除文件的函数
const deleteFile = (filePath) => {
  fs.access(filePath, fs.constants.F_OK, (err) => {
    if (err) {
      // 文件不存在，不需要删除
      console.log(`文件 ${filePath} 不存在，无需删除`);
    } else {
      // 文件存在，执行删除操作
      fs.unlink(filePath, (err) => {
        if (err) {
          // 删除失败，输出错误信息
          console.error(`删除文件 ${filePath} 失败`, err);
        } else {
          // 删除成功
          console.log(`文件 ${filePath} 删除成功`);
        }
      });
    }
  });
};

const UserController = {
  login: async (req, res) => {
    // req是前端传过来的数据，res是后端接口返回的数据

    // 数据查询等操作
    var result = await UserService.login(req.body); //判断前端返回的参数是否正确

    // 处理数据后的返回等操作
    if (result.length === 0) {
      res.send({
        code: "-1",
        error: "用户名密码不匹配",
      });
    } else {
      // 生成token-过期时间：一天
      const token = JWT.generate(
        {
          _id: result[0]._id, //用户id
          username: result[0].username, //用户名
        },
        "1d"
      );
      // token 添加到响应标头 Authorization（授权）
      res.header("Authorization", token);
      res.send({
        ActionType: "OK",
        // 登录成功后，返回用户的信息（密码不返回）
        data: {
          username: result[0].username,
          gender: result[0].gender ? result[0].gender : 0, //性别 ,0,1,2
          introduction: result[0].introduction, //简介
          avatar: result[0].avatar, //头像
          role: result[0].role, //管理员1 ,编辑2
        },
      });
    }
  },

  upload: async (req, res) => {
    const { username, introduction, gender } = req.body;
    const avatar = req.file ? `/images/user/${req.file.filename}` : "";
    const token = req.headers["authorization"].split(" ")[1];
    var payload = JWT.verify(token);

    // 调用service模块更新数据
    await UserService.upload({
      _id: payload._id,
      username,
      introduction,
      gender: Number(gender), //前端传过来的数据可能是字符类型，需确保性别是数字类型
      avatar,
    });

    // 将存储结果告知前端
    const data = {
      username,
      introduction,
      gender: Number(gender),
    };
    if (avatar) data.avatar = avatar;
    res.send({
      ActionType: "OK",
      data: { ...data },
    });
  },

  add: async (req, res) => {
    const { username, password, role, gender, introduction } = req.body;
    const avatar = req.file
        ? `/images/user/${req.file.filename}`
        : "/images/defaultUserImg.png";
    try {
      // 调用服务层添加用户
      await UserService.add({
        username,
        password,
        role: Number(role),
        gender: Number(gender),
        introduction,
        avatar,
      });
      res.send({ ActionType: "OK" });
    } catch (error) {
      // 处理用户名重复错误（MongoDB唯一键冲突错误码11000）
      if (error.code === 11000 && error.message.includes("username")) {
        res.status(400).send({
          ActionType: "ERROR",
          message: "用户名已存在，请更换用户名",
        });
      } else {
        // 其他错误处理
        res.status(500).send({
          ActionType: "ERROR",
          message: "服务器错误，添加用户失败",
        });
      }
    }
  },

  deleteListItem: async (req, res) => {
    const result = await UserService.deleteListItem({ _id: req.params.id });
    res.send({ ActionType: "OK" });
  },

  getListById: async (req, res) => {
    const result = await UserService.getListById(req.params);
    res.send({
      ActionType: "OK",
      data: result,
    });
  },

  getListOfPage: async (req, res) => {
    try {
      // 获取分页参数，默认为第1页，每页10条记录
      const searchValue = req.query.searchValue || ""; // 搜索字段
      const pageNo = parseInt(req.query.pageNo, 10) || 1; // 页码
      const limit = parseInt(req.query.limit, 10) || 10; // 每页数据量
      const sortField = req.query.sortField || "username"; // 默认按用户名排序
      const sortOrder = req.query.sortOrder || "asc"; // 默认升序 [desc|asc]

      const result = await UserService.getListOfPage({
        searchValue,
        pageNo,
        limit,
        sortField,
        sortOrder,
      });

      res.send({
        ActionType: "OK",
        data: {
          pageNo,
          limit,
          ...result,
        },
      });
    } catch (error) {
      res.status(500).send({
        ActionType: "ERROR",
        message: "Failed to fetch users",
      });
    }
  },

  putListItem: async (req, res) => {
    try {
      // 处理文件和数据
      let itemData = { ...req.body }; // 使用解构来复制req.body，避免直接修改它
      itemData.avatar = req.file
        ? `/images/user/${req.file.filename}`
        : req.avatar; // 构建图片的URL

      const currentItme = await UserService.getListById({ id: itemData._id });
      const oldAvatarPath = currentItme[0].avatar;
      // 删除旧的头像文件
      if (
        req.file &&
        oldAvatarPath &&
        oldAvatarPath !== "/images/defaultUserImg.png"
      ) {
        const oldAvatarFullPath = path.join(
          // __dirname, // 返回的是当前执行脚本所在的目录路径
          process.cwd(), // 获取当前工作目录，通常是项目根目录
          "public",
          "images",
          "user",
          path.basename(oldAvatarPath)
        );
        deleteFile(oldAvatarFullPath);
      }
      const result = await UserService.putList(itemData);
      res.send({
        ActionType: "OK",
      });
    } catch (error) {
      console.error("Error:", error);
      res.status(500).send({
        ActionType: "ERROR",
        message: "服务器错误",
        error: error.message,
      });
    }
  },
};

module.exports = UserController;
